import classNames from 'classnames'
import PropTypes from 'prop-types'
import React, { Component } from 'react'
import request from '../utils/request'

export default class TodoMain extends Component {
  static propTypes = {
    list: PropTypes.array,
  }
  async handleDel(id) {
    // 绑定点击事件，调用接口并传递 id
    await request.delete(`/${id}`)
    // 重新获取数据并渲染
    this.props.getDataAndRender()
  }
  // 修改
  async handleChange({ id, done }) {
    await request.patch(`/${id}`, { done: !done })
    this.props.getDataAndRender()
  }
  render() {
    // !#3
    const { list = [] } = this.props
    return (
      <section className='main'>
        <input id='toggle-all' className='toggle-all' type='checkbox' />
        <label htmlFor='toggle-all'>Mark all as complete</label>
        <ul className='todo-list'>
          {list.map((item) => (
            <li
              className={classNames({
                completed: item.done,
              })}
              key={item.id}
            >
              <div className='view'>
                <input
                  className='toggle'
                  type='checkbox'
                  checked={item.done}
                  onChange={() => this.handleChange(item)}
                />
                <label>{item.name}</label>
                <button
                  className='destroy'
                  onClick={() => this.handleDel(item.id)}
                ></button>
              </div>
              {/* <input className='edit' value='Create a TodoMVC template' /> */}
            </li>
          ))}
        </ul>
      </section>
    )
  }
}
